package com.nhjf.admin.controller.system;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nhjf.admin.controller.BaseController;
import com.nhjf.admin.util.Enums;
import com.nhjf.admin.util.Jurisdiction;
import com.nhjf.command.system.CreateRoleCommand;
import com.nhjf.command.system.ModifyRoleCommand;
import com.nhjf.common.page.Pagination;
import com.nhjf.model.system.Resource;
import com.nhjf.model.system.Role;
import com.nhjf.model.system.User;
import com.nhjf.model.teachers.OperationLog;
import com.nhjf.model.ztreeModel.ZtreeModel;
import com.nhjf.pojo.dto.result.ServiceResultDto;
import com.nhjf.pojo.qo.system.ResourceQo;
import com.nhjf.pojo.qo.system.RoleQo;
import com.nhjf.service.system.ResourceService;
import com.nhjf.service.system.RoleService;
import com.nhjf.service.teachers.OperationLogService;

import net.sf.json.JSONArray;

/**
 * @类功能说明：角色管理
 * @部门：技术部
 * @作者：龚一凡
 * @版本：V1.0
 */
@Controller
@RequestMapping(value = "/role")
public class RoleController extends BaseController{
	@Autowired
	private RoleService roleService;
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private OperationLogService operationLogService;
	/**
	 * 
	 * @方法功能说明：角色列表
	 * @修改者名字：龚一凡
	 * @修改时间：2017年8月31日上午9:24:43
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@RequestMapping(value = "/query_role_list")
	public String queryRoleList(HttpServletRequest request, Model model,@ModelAttribute RoleQo roleQo,@RequestParam(value="page", defaultValue="1")Integer page){

		if (roleQo == null) {
			roleQo = new RoleQo();
		}
		Pagination pagination = new Pagination();
		pagination.setPageSize(10);
		pagination.setCondition(roleQo);
		pagination.setPageNo(page);
		pagination = roleService.queryPagination(pagination);
		model.addAttribute("pagination", pagination);
		return "/role/role_list.html";
	}

	/**
	 * 
	 * @方法功能说明：去角色新增页面
	 * @修改者名字：龚一凡
	 * @修改时间：2017年8月31日上午9:24:24
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@RequestMapping(value = "/role_toadd")
	public String toAdd(HttpServletRequest request,Model model){
		ResourceQo resourceQo=new ResourceQo();
		List<Resource>	reslist=resourceService.queryList(resourceQo);//
		List<ZtreeModel> ztreelist=new ArrayList<ZtreeModel>();
		int i=0;
		for(Resource res:reslist) {

			ZtreeModel ztree=new ZtreeModel();
			ztree.setId(res.getId().intValue());
			ztree.setName(res.getName());
			ztree.setpId(res.getParentId().intValue());
			if(res.getId()==281L) {
				ztree.setOpen(true);
			}
			ztreelist.add(ztree);
			//        		System.out.println(res.getName());

		}
		//    	System.out.println(JSONArray.fromObject(ztreelist).toString());
		model.addAttribute("ztreelist",JSONArray.fromObject(ztreelist).toString());
		return "/role/role_add.html";
	}

	/**
	 * 
	 * @方法功能说明：去角色编辑页面
	 * @修改者名字：龚一凡
	 * @修改时间：2017年8月31日上午9:24:00
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@RequestMapping(value = "/role_toedit")
	public String toEdit(HttpServletRequest request,Model model,String id,HttpServletResponse response){
		try {
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}
			ResourceQo resourceQo=new ResourceQo();
			List<Resource>	reslist=resourceService.queryList(resourceQo);//
			ResourceQo userResourceQo=new ResourceQo();
			userResourceQo.setRoleId(Long.parseLong(id));
			List<Resource>	userReslist=resourceService.queryList(userResourceQo);//
			Map<Long, Resource> resMap=new HashedMap();
			for(Resource userRes:userReslist) {
				resMap.put(userRes.getId(), userRes);
			}
			List<ZtreeModel> ztreelist=new ArrayList<ZtreeModel>();
			int i=0;
			for(Resource res:reslist) {

				ZtreeModel ztree=new ZtreeModel();
				ztree.setId(res.getId().intValue());
				ztree.setName(res.getName());
				ztree.setpId(res.getParentId().intValue());
				if(res.getId()==281L) {
					ztree.setOpen(true);
				}
				if(resMap.get(res.getId())!=null) {
					ztree.setChecked(true);
				}
				ztreelist.add(ztree);

			}
			Role role=roleService.get(Long.parseLong(id));
			model.addAttribute("role",role);
			model.addAttribute("ztreelist",JSONArray.fromObject(ztreelist).toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/role/role_edit.html";
	}
	/**
	 * 
	 * @方法功能说明：角色新增
	 * @修改者名字：龚一凡
	 * @修改时间：2017年8月31日上午9:23:36
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value= "/role_save")
	public String save(HttpServletRequest request,HttpServletResponse response,@ModelAttribute CreateRoleCommand role,String ids,Model model) {
		try {
			if(ids==null|| "".equals(ids)) {

			}else {
				String[] split = ids.split("[,]");
				List<Long> idsLong=new ArrayList<Long>();
				for(String id:split) {
					idsLong.add(Long.parseLong(id));
				}
				role.setResourceIdList(idsLong);
			}


			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}

			role.setUser(user);
			ServiceResultDto serviceResultDto=roleService.createRole(role);
			if(serviceResultDto.getSuccess()) {
				OperationLog operationLog=new OperationLog();
				operationLog.setOperationType(2);
				operationLog.setOperationDescription("角色新增!");
				operationLog.setUserId(user);
				operationLog.setOperationTime(new Date());
				operationLog.setOperationUserName(user.getUserName());
				operationLogService.save(operationLog);
				return "200";
			}else {
				return "500";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "500";
	}
	/**
	 * 
	 * @方法功能说明：角色更改
	 * @修改者名字：龚一凡
	 * @修改时间：2017年8月31日上午9:23:12
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value= "/role_update")
	public String update(HttpServletRequest request,HttpServletResponse response,@ModelAttribute ModifyRoleCommand role,String ids,Model model) {
		try {
			if(ids==null|| "".equals(ids)) {

			}else {
				String[] split = ids.split("[,]");
				List<Long> idsLong=new ArrayList<Long>();
				for(String id:split) {
					idsLong.add(Long.parseLong(id));
				}
				role.setResourceIdList(idsLong);
			}

			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}
			role.setUser(user);
			ServiceResultDto serviceResultDto=roleService.modifyRole(role);
			if(serviceResultDto.getSuccess()) {
				OperationLog operationLog=new OperationLog();
				operationLog.setOperationType(3);
				operationLog.setOperationDescription("角色更改!");
				operationLog.setUserId(user);
				operationLog.setOperationTime(new Date());
				operationLog.setOperationUserName(user.getUserName());
				operationLogService.save(operationLog);
				return "200";
			}else {
				return "500";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "500";
	}
	/**
	 * 
	 * @方法功能说明：删除角色
	 * @修改者名字：龚一凡
	 * @修改时间：2017年8月31日上午9:22:25
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value= "/role_delete")
	public String delete(HttpServletRequest request,HttpServletResponse response,String roleId) {
		User user=null;
		try {
			user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}
			roleService.deleteById(Long.parseLong(roleId));

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "500";
		}
		OperationLog operationLog=new OperationLog();
		operationLog.setOperationType(1);
		operationLog.setOperationDescription("角色删除!");
		operationLog.setUserId(user);
		operationLog.setOperationTime(new Date());
		operationLog.setOperationUserName(user.getUserName());
		operationLogService.save(operationLog);
		return "200";
	}

	/**
	 * 
	 * @方法功能说明：角色检测
	 * @修改者名字：龚一凡
	 * @修改时间：2017年9月30日上午11:02:36
	 * @修改内容：
	 * @参数：
	 * @return:
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value= "/role_checkNo")
	public String checkNo(HttpServletRequest request,HttpServletResponse response,String No) {
		try {
			RoleQo qo=new RoleQo();
			qo.setNumber(No);
			Role role=roleService.queryUnique(qo);
			if(role==null) {
				return "200";
			}else {
				return "500";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "500";
		}

	}
}
